import { pageData } from '@/util/util'
import { Prisma, PrismaClient } from '@prisma/client'

/**
 * 定义的公共服务类
 */
export class BaseService<T, D extends Object> {
  protected prisma: PrismaClient

  constructor(private readonly model: Prisma.ModelName) {
    this.prisma = new PrismaClient()
  }

  async create(data: D): Promise<string | null> {
    await this.prisma[this.model].create({
      data,
    })
    return '创建成功'
  }

  async findAll(query: T): Promise<T[]> {
    return await this.prisma[this.model].findMany({
      where: {
        ...query,
      },
    })
  }

  async findOne(id: string): Promise<T | null> {
    return await this.prisma[this.model].findUnique({
      where: {
        id,
      },
    })
  }

  async findPage(query: any): Promise<Result.pageData<T>> {
    return pageData<T>(this.model, query)
  }

  async findById(id: string): Promise<T | null> {
    return this.prisma[this.model].findUnique({
      where: { id },
    })
  }

  async update(id: string, data: D): Promise<string | null> {
    await this.prisma[this.model].update({
      where: { id },
      data,
    })
    return '修改成功'
  }

  async remove(id: string): Promise<string | null> {
    await this.prisma[this.model].delete({
      where: { id },
    })
    return '删除成功'
  }

  async removeMany(ids: string): Promise<string | null> {
    const idList = ids.split(',')
    await this.prisma[this.model].deleteMany({
      where: {
        id: {
          in: idList,
        },
      },
    })
    return '删除成功'
  }
}
